package com.duobaoyu.dby.supply.db.repository.message.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.duobaoyu.dby.supply.db.entity.message.MqMessage;
import com.duobaoyu.dby.supply.db.repository.message.MqMessageRepository;
import com.mongodb.client.result.UpdateResult;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName MqMessageServiceImpl
 * @createTime 11:30:00 2023/10/07
 */
@Repository
@RequiredArgsConstructor
public class MqMessageRepositoryImpl /*extends DbyServiceImpl<MqMessageMapper, MqMessage> */implements MqMessageRepository {

    private final MongoTemplate mongoTemplate;

    @Override
    public boolean save(MqMessage mqMessage) {
        MqMessage save = mongoTemplate.save(mqMessage);
        return Optional.ofNullable(save).map(MqMessage::getId).map(StringUtils::isNotBlank).orElse(false);
    }

    @Override
    public boolean update(Query query, Update update) {
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, MqMessage.class);
        return updateResult.wasAcknowledged();
    }

    @Override
    public Page<MqMessage> page(Page<MqMessage> page,Query query) {
        // 12. 总记录数
        long total = mongoTemplate.count(query, MqMessage.class);
        // 8. 查询返回指定字段 (自定义列表)
        //query.fields().include()
        // 10. 分页、排序
        int pageNo = Long.valueOf(page.getCurrent() - 1).intValue();
        int size = Long.valueOf(page.getSize()).intValue();
        query.with(PageRequest.of(pageNo, size,Sort.by(Sort.Order.desc("create_time"))));
        List<MqMessage> mqMessages = mongoTemplate.find(query, MqMessage.class);
        page.setTotal(total);
        page.setRecords(mqMessages);
        return page;
    }

    @Override
    public MqMessage selectById(String mqMessageId) {
        return mongoTemplate.findById(mqMessageId,MqMessage.class);
    }

    @Override
    public List<MqMessage> mqMessageList(Query query) {

        return mongoTemplate.find(query, MqMessage.class);
    }
}
